package com.wjh.anyview.util;

import com.wjh.anyview.util.constant.IpConstant;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author wjh
 * @date 2021/10/15 13:57
 * @Package com.wjh.anyview.util
 */
public class HttpUtil {
    /**
     * 获取客户端的ip地址
     *
     * @param request 请求HttpServletRequest
     * @return 返回ip地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || IpConstant.UN_KNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || IpConstant.UN_KNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || IpConstant.UN_KNOWN.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals(IpConstant.LOCAL_HOST_IPV4) || ipAddress.equals(IpConstant.LOCAL_HOST_IPV6)) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                if (inet != null) {
                    ipAddress = inet.getHostAddress();
                } else {
                    ipAddress = "unknown";
                }
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > IpConstant.IP_LENGTH) {
            if (ipAddress.indexOf(IpConstant.COMMA) > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(IpConstant.COMMA));
            }
        }
        return ipAddress;
    }
}
